import PageView from "@/components/base/page";
import { taskEntity } from "@/drizzle/model/taskEntity";
import { useColor } from "@/hooks/color";
import { useLoadedFontFamilyByAction } from "@/hooks/font";
import { useUpdateForm } from "@/hooks/task.form";
import { TaskSelect } from "@/stores/tasks/item";
import { eq } from "drizzle-orm";
import { router, useLocalSearchParams } from "expo-router";
import React, { createContext, useContext, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { ActionSheet, Button, Colors, Text, TouchableOpacity, View, ViewProps } from "react-native-ui-lib";
export enum TaskType {
  CREATE_TASK = "2008",
  EDIT_TASK = "2009",
}
enum ActionNumberType {
  CLOSE_MODAL = 0,
  CREATE_TASK = 1,
  EDIT_TASK = 2,
}

export interface IAddTaskTypeItemsProps {
  action?: string;
  button?: string;
}

export const BaseAddTaskCore = createContext<{
  type: TaskType;
  item: TaskSelect;
  setItem: React.Dispatch<React.SetStateAction<TaskSelect>>;
  setType: React.Dispatch<React.SetStateAction<TaskType>>;
  isActionSheetVisible: boolean;
  setActionSheetVisible: React.Dispatch<React.SetStateAction<boolean>>;
  actionNumber: number;
  setActionNumber: React.Dispatch<React.SetStateAction<number>>;
  useTitle: Record<TaskType, IAddTaskTypeItemsProps>;
  actionSheetOptions: React.ComponentProps<typeof ActionSheet>["options"];
}>({
  type: TaskType.CREATE_TASK,
  item: {} as TaskSelect,
  setItem: () => {},
  setType: () => {},
  isActionSheetVisible: false,
  setActionSheetVisible: () => {},
  actionNumber: 0,
  setActionNumber: () => {},
  useTitle: {
    [TaskType.CREATE_TASK]: {},
    [TaskType.EDIT_TASK]: {},
  },
  actionSheetOptions: [],
});
const BaseAddTaskProvider: React.FC<ViewProps> = ({ children }) => {
  // 类型
  const [type, setType] = useState<TaskType>(TaskType.CREATE_TASK);
  // 任务数据
  const [item, setItem] = useState<TaskSelect>({} as TaskSelect);
  // 是否显示modal 弹框
  const [isActionSheetVisible, setActionSheetVisible] = useState(false);
  // modal 弹框的选项 0:确认删除 1:取消
  const [actionNumber, setActionNumber] = useState<ActionNumberType>(ActionNumberType.CLOSE_MODAL);
  const useTitle: Record<TaskType, IAddTaskTypeItemsProps> = {
    [TaskType.CREATE_TASK]: {
      action: useTranslation().t("2008"),
      button: useTranslation().t("3005"),
    },
    [TaskType.EDIT_TASK]: {
      action: useTranslation().t("2009"),
      button: useTranslation().t("3005"),
    },
  };

  const actionSheetOptions: React.ComponentProps<typeof ActionSheet>["options"] = [
    {
      label: useTranslation().t("4002"),
      onPress: () => setActionNumber(1),
      labelStyle: { color: Colors.getColorTint(useColor().color.error, 20), ...useLoadedFontFamilyByAction("SPACE_MONO") },
    },
    {
      label: useTranslation().t("4003"),
      onPress: () => setActionNumber(2),
      labelStyle: { color: Colors.getColorTint(useColor().color.action, 20), ...useLoadedFontFamilyByAction("SPACE_MONO") },
    },
  ];

  return (
    <BaseAddTaskCore.Provider
      value={{
        type,
        setType,
        item,
        setItem,
        isActionSheetVisible,
        setActionSheetVisible,
        actionNumber,
        setActionNumber,
        useTitle,
        actionSheetOptions,
      }}>
      {children}
    </BaseAddTaskCore.Provider>
  );
};

const AddTaskItem: React.FC<ViewProps> = ({ children }) => {
  const prams = useLocalSearchParams<{ type?: keyof typeof TaskType; item?: string }>();
  const query = useContext(BaseAddTaskCore);

  useEffect(() => {
    query.setActionSheetVisible(false);
    query.setActionNumber(0);
    query.setType(prams.type ? (prams.type as TaskType) : TaskType.CREATE_TASK);
    query.setItem(prams?.item ? (JSON.parse(prams.item.toString()) as TaskSelect) : ({} as TaskSelect));
  }, []);

  useEffect(() => {
    if (query.actionNumber == 1) {
      useUpdateForm
        .set({
          isDeleted: true,
        })
        .where(eq(taskEntity.id, query.item.id))
        .execute()
        .then(res => {
          if (router.canGoBack() && res.changes > 0) router.back();
        })
        .catch(error => {
          alert(error.message);
        });
    }
    query.setActionNumber(0);
    query.setActionSheetVisible(false);
  }, [query.actionNumber]);

  return (
    <PageView>
      <View flex centerH useSafeArea padding-6>
        <Text style={{ color: Colors.getColorTint(useColor().colors.text, 30), ...useLoadedFontFamilyByAction("SONG_BAIT") }} text60>
          {query.useTitle[query.type].action}
        </Text>
        <TouchableOpacity
          className='absolute right-0 top-1'
          style={{ display: query.type === TaskType.EDIT_TASK ? "flex" : "none" }}
          onPress={() => query.setActionSheetVisible(true)}>
          <Text
            text70
            style={{ color: Colors.getColorTint(useColor().color.error, 30), ...useLoadedFontFamilyByAction("SPACE_MONO") }}
            className='font-bold'>
            {useTranslation().t("3006")}
          </Text>
        </TouchableOpacity>
        {children}
      </View>
      <ActionSheet
        title={useTranslation().t("4001")}
        options={query.actionSheetOptions}
        cancelButtonIndex={query.actionSheetOptions?.length}
        visible={query.isActionSheetVisible}
        onDismiss={() => query.setActionSheetVisible(false)}
      />
    </PageView>
  );
};

const TaskChangeView: React.FC<ViewProps> = ({ children }) => {
  return (
    <BaseAddTaskProvider>
      <AddTaskItem>{children}</AddTaskItem>
    </BaseAddTaskProvider>
  );
};

export default TaskChangeView;
